#******************************************************************
#
# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
#
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

##
# liboctbstack (share library) build script
##
Import('env')
import os

liboctbstack_env = env.Clone()

# Build C Samples
SConscript('samples/SConscript',
           exports={'stacksamples_env': liboctbstack_env})

SConscript('#/resource/third_party_libs.scons',
           exports={'lib_env': liboctbstack_env})

target_os = env.get('TARGET_OS')
rd_mode = env.get('RD_MODE')
with_ra = env.get('WITH_RA')
with_ra_ibb = env.get('WITH_RA_IBB')
with_tcp = env.get('WITH_TCP')
with_cloud = env.get('WITH_CLOUD')
with_mq = env.get('WITH_MQ')

######################################################################
# Build flags
######################################################################
with_upstream_libcoap = liboctbstack_env.get('WITH_UPSTREAM_LIBCOAP')
if with_upstream_libcoap == '1':
    liboctbstack_env.PrependUnique(CPPPATH=['#extlibs/libcoap/libcoap/include'])
else:
    liboctbstack_env.PrependUnique(CPPPATH=['#resource/csdk/connectivity/lib/libcoap-4.1.1/include'])

liboctbstack_env.PrependUnique(CPPPATH=[
    '#resource/c_common/octimer/include',
    '#resource/c_common/ocatomic/include',
    '#resource/csdk/logger/include',
    '#resource/csdk/include',
    'include',
    'include/internal',
    '#resource/oc_logger/include',
    '#resource/csdk/connectivity/common/inc',
    '#resource/csdk/connectivity/inc',
    '#resource/csdk/connectivity/inc/pkix',
    '#resource/csdk/connectivity/api',
    '#resource/csdk/connectivity/external/inc',
    '#resource/csdk/security/include',
    '#resource/csdk/security/include/internal',
    '#resource/csdk/security/provisioning/include',
    '#resource/csdk/routing/include',
])

if 'SUB' in with_mq:
    liboctbstack_env.AppendUnique(CPPDEFINES=['MQ_SUBSCRIBER', 'WITH_MQ'])
if 'PUB' in with_mq:
    liboctbstack_env.AppendUnique(CPPDEFINES=['MQ_PUBLISHER', 'WITH_MQ'])
if 'BROKER' in with_mq:
    liboctbstack_env.AppendUnique(CPPDEFINES=['MQ_BROKER', 'WITH_MQ'])

if target_os not in ['windows']:
    liboctbstack_env.AppendUnique(CPPDEFINES=['WITH_POSIX', '_GNU_SOURCE'])
    liboctbstack_env.AppendUnique(CFLAGS=['-std=c99'])

if liboctbstack_env.get('ROUTING') == 'GW':
    liboctbstack_env.AppendUnique(CPPDEFINES=['ROUTING_GATEWAY'])
elif liboctbstack_env.get('ROUTING') == 'EP':
    liboctbstack_env.AppendUnique(CPPDEFINES=['ROUTING_EP'])

if target_os not in ['windows']:
    liboctbstack_env.AppendUnique(CFLAGS=['-Wall'])

if target_os in ['tizen']:
    liboctbstack_env.AppendUnique(LIBS = ['pthread'])

liboctbstack_env.PrependUnique(LIBS=['ocsrm', 'coap'])

if target_os in ['linux'] and liboctbstack_env.get('SIMULATOR', False):
    liboctbstack_env['RPATH']=liboctbstack_env.Literal('\\$$ORIGIN')

if env.get('SECURED') == '1':
    liboctbstack_env.AppendUnique(LIBS=['mbedtls', 'mbedx509'])

# c_common calls into mbedcrypto.
liboctbstack_env.AppendUnique(LIBS=['mbedcrypto'])

if target_os in ['android', 'linux', 'tizen', 'msys_nt', 'windows', 'webos']:
    if target_os not in ['windows', 'msys_nt']:
        liboctbstack_env.PrependUnique(LIBS=['connectivity_abstraction'])
    else:
        # On Windows, apps don't link directly with connectivity_abstraction.
        # connectivity_abstraction is linked inside octbstack.dll and apps
        # import its APIs by linking with octbstack.lib.
        liboctbstack_env.PrependUnique(LIBS=['connectivity_abstraction_internal'])

    if with_ra_ibb:
        liboctbstack_env.AppendUnique(
            LIBS=liboctbstack_env['RALIBS'],
            LIBPATH=liboctbstack_env['RALIBPATH'],
            RPATH=liboctbstack_env['RARPATH'])
    else:
        if with_ra:
            liboctbstack_env.AppendUnique(LIBS=['ra_xmpp'])

if target_os not in ['windows', 'msys_nt']:
    liboctbstack_env.AppendUnique(LIBS=['m'])
else:
    # octbstack.def specifies the list of functions exported by octbstack.dll.
    liboctbstack_env.Replace(WINDOWS_INSERT_DEF=['1'])

    # On Windows, apps don't link directly with oc_logger. oc_logger is linked inside
    # octbstack.dll and apps import its APIs by linking with octbstack.lib.
    liboctbstack_env.PrependUnique(LIBS=['oc_logger_internal'])

    if 'CLIENT' in rd_mode or 'SERVER' in rd_mode:
        # On Windows:
        # - octbstack.dll is exporting resource_directory C APIs
        # - resource_directory.lib contains just the implementation of the C++ RD APIs
        liboctbstack_env.PrependUnique(LIBS=['resource_directory_internal'])

    if 'CLIENT' in rd_mode:
        liboctbstack_env.Textfile(
            target='octbstack_temp1.def',
            source=[
                File('octbstack_product.def'),
                File('octbstack_rd_client.def')
            ])
    else:
        liboctbstack_env.Textfile(
            target='octbstack_temp1.def',
            source=[File('octbstack_product.def')])

    if 'SERVER' in rd_mode:
        liboctbstack_env.Textfile(
            target='octbstack_temp2.def',
            source=[
                File('octbstack_temp1.def'),
                File('octbstack_rd_server.def')
            ])
    else:
        liboctbstack_env.Textfile(
            target='octbstack_temp2.def', source=[File('octbstack_temp1.def')])

    if env.get('SECURED') != '1':
        liboctbstack_env.Textfile(
            target='octbstack.def', source=[File('octbstack_temp2.def')])
    else:
        # On Windows, apps don't link directly with ocpmapi.lib. ocpmapi is linked
        # inside octbstack.dll and apps import its APIs by linking with octbstack.lib.
        liboctbstack_env.PrependUnique(LIBS=['ocpmapi_internal'])

        liboctbstack_env.Textfile(
            target='octbstack_temp3.def',
            source=[
                File('octbstack_temp2.def'),
                File('octbstack_product_secured.def')
            ])

        if env.get('MULTIPLE_OWNER') == '1':
            liboctbstack_env.Textfile(
                target='octbstack.def',
                source=[
                    File('octbstack_temp3.def'),
                    File('octbstack_product_secured_mot.def')
                ])
        else:
            liboctbstack_env.Textfile(
                target='octbstack.def', source=[File('octbstack_temp3.def')])

if target_os in ['tizen', 'linux', 'webos']:
    liboctbstack_env.ParseConfig("pkg-config --cflags --libs uuid")
    liboctbstack_env.ParseConfig('pkg-config --cflags --libs sqlite3')

if target_os not in ['darwin', 'ios', 'msys_nt', 'windows']:
    liboctbstack_env.AppendUnique(CFLAGS=['-fPIC'])
if target_os in ['darwin', 'ios']:
    env.AppendUnique(CPPDEFINES=['_DARWIN_C_SOURCE'])
    liboctbstack_env.AppendUnique(CPPDEFINES=['_DARWIN_C_SOURCE'])
if target_os not in ['windows']:
    liboctbstack_env.AppendUnique(LINKFLAGS=['-Wl,--no-undefined'])
if target_os == 'android':
    liboctbstack_env.AppendUnique(LINKFLAGS=['-Wl,-soname,liboctbstack.so'])

if env.get('LOGGING'):
    liboctbstack_env.AppendUnique(CPPDEFINES=['TB_LOG'])

if liboctbstack_env.get('ROUTING') in ['GW', 'EP']:
    liboctbstack_env.Prepend(LIBS=['routingmanager'])

if 'CLIENT' in rd_mode or 'SERVER' in rd_mode:
    liboctbstack_env.PrependUnique(CPPPATH=['#/resource/csdk/resource-directory/include'])

    if target_os in ['windows']:
        liboctbstack_env.AppendUnique(LIBS=['sqlite3'])

    if 'CLIENT' in rd_mode:
        liboctbstack_env.AppendUnique(CPPDEFINES=['RD_CLIENT'])

    if 'SERVER' in rd_mode:
        liboctbstack_env.AppendUnique(CPPDEFINES=['RD_SERVER'])
        if target_os not in ['tizen', 'webos']:
            # tizen added via pkg-config above
            liboctbstack_env.AppendUnique(CPPPATH=['#/extlibs/sqlite3'])

######################################################################
# Source files and Targets
######################################################################
OCTBSTACK_SRC = 'src/'
liboctbstack_src = [
    OCTBSTACK_SRC + 'ocstack.c',
    OCTBSTACK_SRC + 'ocpayload.c',
    OCTBSTACK_SRC + 'ocpayloadparse.c',
    OCTBSTACK_SRC + 'ocpayloadconvert.c',
    OCTBSTACK_SRC + 'occlientcb.c',
    OCTBSTACK_SRC + 'ocresource.c',
    OCTBSTACK_SRC + 'ocobserve.c',
    OCTBSTACK_SRC + 'ocserverrequest.c',
    OCTBSTACK_SRC + 'occollection.c',
    OCTBSTACK_SRC + 'ocatomicmeasurement.c',
    OCTBSTACK_SRC + 'oicgroup.c',
    OCTBSTACK_SRC + 'ocendpoint.c'
]

if with_tcp == True:
    liboctbstack_src.append(OCTBSTACK_SRC + 'oickeepalive.c')
    if with_cloud == True:
        liboctbstack_src.append(OCTBSTACK_SRC + 'occonnectionmanager.c')

if 'SERVER' in rd_mode:
    liboctbstack_src.append(OCTBSTACK_SRC + 'oicresourcedirectory.c')
    if target_os not in ['linux', 'tizen', 'windows', 'webos']:
        liboctbstack_src.append('#extlibs/sqlite3/sqlite3.c')

if ((target_os in ['windows']) and (liboctbstack_env.get('MSVC_UWP_APP') == '1')):
    liboctbstack_src.append(OCTBSTACK_SRC + 'ocsqlite3helper.c')

internal_liboctbstack = liboctbstack_env.StaticLibrary(
    'octbstack_internal', liboctbstack_src)
octbstack_libs = Flatten(internal_liboctbstack)

if target_os not in ['darwin', 'ios']:
    shared_liboctbstack = liboctbstack_env.SharedLibrary(
        'octbstack', liboctbstack_src)
    octbstack_libs += Flatten(shared_liboctbstack)
    liboctbstack_env.UserInstallTargetHeader('include/ocstack.h', 'resource/stack', 'ocstack.h')
    liboctbstack_env.UserInstallTargetHeader('include/ocpresence.h', 'resource/stack', 'ocpresence.h')

if target_os not in ['windows', 'msys_nt']:
    static_liboctbstack = liboctbstack_env.StaticLibrary(
        'octbstack', liboctbstack_src)
    octbstack_libs += Flatten(static_liboctbstack)

liboctbstack_env.InstallTarget(octbstack_libs, 'octbstack')
liboctbstack_env.UserInstallTargetLib(octbstack_libs, 'octbstack')

liboctbstack_env.UserInstallTargetHeader('include/ocstackconfig.h', 'resource/stack', 'ocstackconfig.h')
liboctbstack_env.UserInstallTargetHeader('include/ocpayload.h', 'resource/stack', 'ocpayload.h')
liboctbstack_env.UserInstallTargetHeader('include/experimental/payload_logging.h',
                                         'resource/stack/experimental', 'payload_logging.h')
